package com.luoxin.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.luoxin.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    // 盐
    private static final String SALT = "CPFmsb!@#$$";
    private static final String JWT_KEY_PHONE = "passengerPhone";
    /**
     * 乘客是1 司机是2
     */
    private static final String JWT_KEY_IDENTITY = "identity";
    /**
     * tokenType
     */
    private static final String JWT_KEY_TOKEN_TYPE = "tokenType";
    /**
     * token生成时间
     */
    private static final String JWT_TOKEN_TIME = "tokenTime";
    public static String geneJsonWebToken(String phone,String identity,String tokenType){
        Map<String,String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,phone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_KEY_TOKEN_TYPE,tokenType);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        Date date = instance.getTime();
        map.put(JWT_TOKEN_TIME,date.getTime()+"");

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v) -> {
            builder.withClaim(k,v);
        });

        /*// 整合过期时间(这里将过期时间交给redis去控制)
        builder.withExpiresAt(date);*/

        // 生成token
        String token = builder.sign(Algorithm.HMAC256(SALT));
        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static TokenResult parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    /**
     * 校验token，主要判断token是否异常
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token){
        TokenResult tokenResult = null;
        try {
            tokenResult = JwtUtils.parseToken(token);
        }catch (Exception e){

        }
        return tokenResult;
    }
}
